
#include "dev/time.h"
#include "comm/types.h"
#include "comm/cpu_instr.h"
#include "os.cfg.h"
#include "core/task.h"

// define system ticks
static uint32_t sys_tick;

//
uint32_t reload_count = PIT_OSC_FREQ / (1000.0 / OS_TICKS_MS);
/**
 * 定时器中断处理函数
 */
void do_handler_time(exception_frame_t *frame){
    sys_tick++;
    // 先发EOI，而不是放在最后
    // 放最后将从任务中切换出去之后，除非任务再切换回来才能继续噢应
    pic_send_eoi(IRQ0_TIME);
    // 调用函数经常时间片递减，为0切换函数
    task_time_tick();
}

// pic=Programmable interrupt
/**
 * 初始化硬件定时器
 */
void init_pit(void)
{
    outb(PIT_COMMAND_MOOE_PORT, PIT_CHANNEL | PIT_LOAD_LOHI | PIT_MODE3);
    outb(PIT_CHANNEL0_DATA_PORT, (reload_count)&0xff);
    outb(PIT_CHANNEL0_DATA_PORT, (reload_count >> 8) & 0xff);
}
/**
 * 定时器初始化
 */
void time_init(void)
{
    sys_tick = 0;
    init_pit();

    // install time interrupt
    irq_install(IRQ0_TIME, (irq_handler_t)exception_handler_time);
    irq_enable(IRQ0_TIME);
}
